<?php
date_default_timezone_set("PRC");

$root = dirname($argv[0]);
$templatePath= "$root/template/";
if($argc<=1){
	$info = <<<EOL
	usage:tpl   html/index.html path/to/target.html  age=fdaf  some=fdafadsf
	
EOL;
	die($info);
}
$path = $templatePath.$argv[1];
if(is_dir($path)){
	$path = $path.'/index.tpl';
}
if(!file_exists($path)){
	die('tpl not find;');
}
function toTplArray($data){
	$result=array();
	foreach($data as $k=>$v){
		$result['{%'.$k.'%}']=$v;
	}
	return $result;
}
function tplTranslate($tpl,$arr){
	return strtr($tpl,toTplArray($arr));
}
//$tmp = toTplArray(['age'=>18,'sex'=>20]);
//var_dump($tmp);exit;
//exit;
//提示输入
function inputOption($arr){
	
}

//直接用include方式，加载，并执行
ob_start();
include  $path;
$tpl = ob_get_contents();
ob_end_clean();

//变量替换
$cfg = require('cfg.php');
$tpl = tplTranslate($tpl,$cfg);

//目标变量
if(file_exists($argv[2])){
	echo 'File exists,are you wanna overwrite?  yes or no:';
	$msg = strtolower(trim(fgets(STDIN)));
	if($msg=='y' or  $msg=='yes'){
		echo  'overwrite';
	}else{
		die('not overwrite');
	}
}
//建立目录
if(strpos($argv[2],'/')){
	mkdir(dirname($argv[2]),0777,true);
}

file_put_contents($argv[2],$tpl);